package com.laopan.wxpay.utils;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * json 的转换，默认采用gson.
 *
 * @author laopan
 * @className HttpUtils
 * @date 2021/2/22 13:46
 */
public class JsonUtils {
    private static Gson gson;

    static {
        gson = new Gson();
    }

    public static String toJson(Object obj) {
        return gson.toJson(obj);
    }

    /**
     * long数据转换成String
     *
     * @param obj
     * @return
     */
    public static String toLongJson(Object obj) {
        Gson gsonBuilder = new GsonBuilder()
                .setLongSerializationPolicy(LongSerializationPolicy.STRING)
                .create();
        return gsonBuilder.toJson(obj);
    }

    public static <T> T fromJson(String jsonStr, Class<T> cls) {
        return gson.fromJson(jsonStr, cls);
    }

    public static JsonObject toJsonTree(Object obj) {
        return (JsonObject) gson.toJsonTree(obj);
    }

    public static String getFiledData(Object obj, String filed) {
        JsonObject jsonObject = toJsonTree(obj);
        return jsonObject.get(filed).getAsString();
    }

    public static <T> JsonArray toJsonArray(Object obj, Class<T> cls) {
        return gson.toJsonTree(obj, new TypeToken<List<T>>() {
        }.getType()).getAsJsonArray();
    }

    public static Map<String, String> toMap(Object obj) {
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        String json = gson.toJson(obj);
        Type type = new TypeToken<Map<String, String>>() {
        }.getType();
        return gson.fromJson(json, type);
    }
}
